package com.zzyl.service.impl;

import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.CustomerUserMapper;
import com.zzyl.service.CustomerUserService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class CustomerUserServiceImpl implements CustomerUserService {
    @Autowired
    private WeChatService weChatService;

    @Autowired
    private CustomerUserMapper customerUserMapper;

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String base64EncodedSecretKey;

    @Value("${zzyl.framework.jwt.ttl}")
    private Integer ttl;

    private static List<String> DEFAULT_NICKNAME_PREFIX = List.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        String phoneNumber = weChatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());

        Member member = customerUserMapper.getByOpenId(openId);
        if(member == null){
            member = new Member();
            String nickName = DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()))+phoneNumber.substring(7);
            member.setName(nickName);
            member.setPhone(phoneNumber);
            member.setOpenId(openId);
            customerUserMapper.insertUser(member);
        }else {
            if(!phoneNumber.equals(member.getPhone())){
                member.setPhone(phoneNumber);
                customerUserMapper.updateUser(member);
            }
        }
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        Map map = new HashMap();
        map.put("nickName",member.getName());
        map.put("id",member.getId());
        String token = JwtUtil.createJWT(base64EncodedSecretKey, ttl, map);
        loginVo.setToken(token);
        return loginVo;
    }
}
